using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class TerrainGeneration : MonoBehaviour
{
    public static TerrainGeneration _instance;
    public void Awake()
    {
        _instance = this;
    }

    public GameObject plane;
    [Range(0, 10)]
    public float space;
    public int obstacleRate = 80;

    public Vector2 startPos;
    public Vector2 endPos;
    private int counter=0;

    private Ray ray;
    private RaycastHit hit;

    // Start is called before the first frame update
    void Start()
    {
        Build();
    }

    // Update is called once per frame
    void Update()
    {
        ChooseCube();
    }

    private void Build()
    {
        GameObject gameObject = new GameObject("Cubes");
        for (int i = 0; i < 10; i++)
        {
            for (int j = 0; j < 10; j++)
            {
                //Debug.Log(i + " " + j);
                GameObject obj= Instantiate(plane, new Vector3(space*i, space*j, 0), Quaternion.identity);

                obj.GetComponentInChildren<Text>().text = "(" + i + "," + j + ")";
                obj.name = "(" + i + "," + j + ")";
                obj.GetComponent<CubeInfo>().SetPos(i, j);
                obj.transform.parent = gameObject.transform;
                if (Random.Range(0,100)>=obstacleRate)
                {
                    obj.GetComponent<MeshRenderer>().material.color = Color.red;
                    obj.GetComponent<CubeInfo>().cubeType = CubeType.cannotWalk;
                }
                AStar._instance.objArr[i, j] = obj.GetComponent<CubeInfo>();
                Debug.Log(obj.name);
            }
        }
    }

    private void ChooseCube()
    {
        if(Input.GetMouseButtonDown(0))
        {
            //Debug.Log("press mouse 0");
            ray = Camera.main.ScreenPointToRay(Input.mousePosition);
            if(Physics.Raycast(ray,out hit))
            {
                Debug.Log(hit.collider.gameObject.name);
                hit.collider.gameObject.GetComponent<MeshRenderer>().material.color = Color.green;
                if(counter==0)
                {
                    startPos.x = hit.collider.gameObject.GetComponent<CubeInfo>().x;
                    startPos.y = hit.collider.gameObject.GetComponent<CubeInfo>().y;
                    counter++;
                    AStar._instance.openLists.Clear();
                    AStar._instance.closeLists.Clear();
                }
                else
                {
                    endPos.x = hit.collider.gameObject.GetComponent<CubeInfo>().x;
                    endPos.y = hit.collider.gameObject.GetComponent<CubeInfo>().y;
                    //TODO
                    counter--;
                    AStar._instance.Astar_Connect();
                }
            }
        }
    }
}
